<template>
  <div :id="chartId" :style="{'height':height}" class="echarts-box" />
</template>

<script>
  // vue
  import {
    defineComponent,
    toRefs,
    onMounted,
    watch,
    ref
  } from 'vue'
  // echarts
  import * as echarts from 'echarts'
  // options
  import {
    Line3Data
  } from './Line3'

  export default defineComponent({
    props: {
      chartId: {
        type: String,
        default: 'myId'
      },
      chartData: {
        type: Object,
        default: function () {
          return {}
        }
      },
      height: {
        type: String,
        default: '300px'
      }
    },
    setup(props) {
      const {
        chartId,
        chartData,
        height
      } = toRefs(props)
      // 初始化echarts实例
      let myChart = ref()
      let myChartFlag = ref(false)
      watch(
        () => chartData.value,
        (val, prevVal) => {
          if (myChartFlag.value) {
            myChart.value.setOption({
              xAxis: {
                data: val.xdata
              },
              series: [{
                data: val.ydata
              }]
            })
          }
        }, {
          deep: true
        }
      )
      onMounted(async () => {
        myChart.value = echarts.init(document.getElementById(chartId.value))
        // 绘制图表
        myChart.value.setOption(Line3Data,{
        notMerge: false,
        lazyUpdate: false,
        silent: false
      })
        myChartFlag.value = true
        window.addEventListener('resize', () => {
          myChart.value.resize();
        })
      })
      return {
        chartId,
        chartData,
        height,
        myChart,
        myChartFlag
      }
    }
  })
</script>

<style lang="scss" scoped>
  .echarts-box {
    width: 100%;
  }
</style>